<?php
/**
 * Hiển thị output từ template
 */
class Template
{
    public static $styleFolder = 'styles';
    public $style = 'default';

    /**
     * Tên template
     * @var string
     */
    public $templateName = '';

    /**
     * Tên layout
     * @var string
     */
    public $layoutName = '';

    /**
     * Tham số cho template
     * @var array
     */
    public $params = array();

    /**
     * Tham số thêm cho layout
     * @var array
     */
    public $layoutParams = array();

    public function fetchContent()
    {
        if ($this->templateName == '')
        {
            return '';
        }

        $templateFolderPath = BASE_PATH . self::$styleFolder . '/' . $this->style . '/template/';

        $this->_prepareparams();

        $output = self::fetchTemplate($templateFolderPath . $this->templateName . '.php',
            $this->params
        );

        if ($this->layoutName != '')
        {
            $this->layoutParams['body'] = $output;

            $output = self::fetchTemplate($templateFolderPath . $this->layoutName . '.php',
                $this->layoutParams
            );
        }

        return $output;
    }

    protected function _prepareparams()
    {
        // Style path
        $stylePath = self::$styleFolder . '/' . $this->style . '/';
        $this->layoutParams['stylePath'] = $this->params['stylePath'] = $stylePath;
    }

    public static function fetchTemplate($templatePath, array $params = array())
    {
        if (file_exists($templatePath))
        {
            if (is_array($params))
            {
                extract($params);
            }

            // Buffer output
            ob_start();

            include($templatePath);

            $content = ob_get_contents();

            ob_end_clean();

            return $content;
        }
        else
        {
            throw new Exception('Can not fetch template: ' . $templatePath);
        }
    }
}